import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';

/*
* WidgetPage基类封装
* 2019-12-31
* ZhongWb
* Doc：子类继承此类即可，继承后 build方法不可重写，改重写buildBody 、buildAppBar
* */
class BasePage extends State {
  StreamSubscription<ConnectivityResult> _connectivitySubscription;
  ///todo:网络状态
  int netWorkState = -1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //启动监听
    connectivityInitState();
    //开始监听
    setState(() {});
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    //网络状态监听结束
    connectivityDispose();
  }


  @override
   Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
      body: Column(
        children: <Widget>[
          //DIP 提示组件
          tipWidget(),
          //Body组件
          Expanded(
            child: buildBody(context),
          ),
        ],
      ),
      bottomNavigationBar:buildBottomNav(context),
    );
  }

  //buildBottomNav 底部导航 子类需重写次方法,protected只有子类能调用
  @protected
  Widget buildBottomNav(BuildContext context){
    return null;
  }

  //Body 子类需重写次方法,protected只有子类能调用
  @protected
  Widget buildBody(BuildContext context){
    return null;
  }

  //AppBar 子类需重写次方法,protected只有子类能调用
  @protected
  PreferredSizeWidget buildAppBar(BuildContext context){
    return AppBar();
  }

  //网络初始状态  0:没有网络  1:移动网络    2:wifi网络
  connectivityInitState() {
    try {
      _connectivitySubscription = Connectivity()
          .onConnectivityChanged
          .listen((ConnectivityResult result) {
        print(">>> 网络状态：" + result.toString());
        if (result == ConnectivityResult.mobile) {
          setState(() {
            netWorkState = 1;
          });
        } else if (result == ConnectivityResult.wifi) {
          setState(() {
            netWorkState = 2;
          });
        } else if (result == ConnectivityResult.none){
          setState(() {
            netWorkState = 0;
          });
        }else{
          //出现异常
          setState(() {
            netWorkState = -1;
          });
        }
      });
    } catch (e) {
      print("网络监听出现异常:" + e.toString());
    }
  }

  //网络结束监听
  connectivityDispose() {
    _connectivitySubscription.cancel();
  }

  //没有网络 TIP提示组件,protected只有子类能调用
  @protected
  Widget tipWidget() {
    return netWorkState == 0
        ? Container(
            width: MediaQuery.of(context).size.width,
            height: 48,
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.all(10),
            child: Row(
              children: <Widget>[
                Icon(
                  Icons.error,
                  color: Colors.red,
                ),
                Text("当前网络不可用，请检查你的网络设置"),
              ],
            ),
            color: Color(0xffFFECEE),
          )
        : Container(height: 0,);
  }
}
